<?php
/**
 * 文章属性表
 * User: Lin Hui
 * Date: 2017/5/18
 * Time: 13:46
 */

namespace Common\Model;


use Think\Model;

class ArticleAttributesModel extends Model
{
    public $types = array();

    /**
     * 获取文章属性
     * @param int $article_id 文章ID
     * @return array
     */
    public function getAttributes($article_id)
    {
        $types_config = C('ARTICLE.attribute');
        $result = array();
        if(!$this->types){
            $this->types = $this->group('type')->getField('type', true);
        }
        foreach ($this->types as $type) {
            if ($type && array_key_exists ($type, $types_config)) {
                $result[$types_config[$type]] = $this->where(array('article_id'=>$article_id, 'type'=>$type))->getField('value', true);
            }
        }
        return $result;
    }

    /**
     * 设置文章属性
     * @param int $article_id
     * @param string $type
     * @param array $value
     * @return bool
     */
    public function setAttributes($article_id, $type, $value = array())
    {
        $types_config = C('ARTICLE.attribute');
        if(!is_numeric($article_id) || !in_array($type, $types_config)){
            return false;
        }

        $this->where(array('article_id'=>$article_id, 'type'=>array_search($type, $types_config)))->delete();
        $add = array();
        foreach($value  as $item) {
            $add[] = array(
                'article_id'=>$article_id,
                'type'=>array_search($type, $types_config),
                'value'=>$item,
            );
        }

        if($this->addAll($add)) {
            return true;
        } else {
            return false;
        }

    }
}